package com.lagou.edu.factory;

import com.lagou.edu.annotation.MyAnnotation;
import com.lagou.edu.utils.TransactionManager;
import com.lagou.edu.annotation.MyAnnotation.Transactional1;


import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    private ProxyFactory() {

    }

    private static ProxyFactory proxyFactory = new ProxyFactory();

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }

//    private TransactionManager transactionManager;
//
//    public void setTransactionManager(TransactionManager transactionManager) {
//        this.transactionManager = transactionManager;
//    }

    public Object getJdkProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Object result = null;

                Annotation annotation = method.getAnnotation(Transactional1.class);

                if(annotation != null) {
                    try{

                        // 开启事务 (关闭事务的自动提交)
                        TransactionManager.getInstance().beginTransaction();

                        result = method.invoke(o, args);

                        // 提交事务
                        TransactionManager.getInstance().commit();

                    }catch (Exception e) {
                        // 回滚事务
                        e.printStackTrace();
                        TransactionManager.getInstance().rollback();
                        throw e;
                    }
                }else {
                    result = method.invoke(o, args);
                }

                return result;
            }
        });

    }

}
